<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>关联食堂</title>
    <link rel="stylesheet" href="plugins/layui/css/layui.css" media="all" />
    <link rel="stylesheet" href="css/comments.css" media="all">
    <style>
        .layui-form-label{
            width: 150px;
        }
        .layui-input-block{
            margin-left: 180px;
        }
		#tableForm{
			display: none;
            padding: 10px 20px;
		}
    </style>
</head>
<body>
    <div class="maincontainer">
        <blockquote class="layui-elem-quote">
            关联食堂
            <button type="button" class="layui-btn layui-btn-sm" style="float: right;margin-top: -4px;" onclick="window.history.back();">返回</button>
        </blockquote>
        <form class="layui-form" action="" lay-filter="example">
            <div class="layui-form-item">
                <label class="layui-form-label">食堂等级：</label>
                <div class="layui-form-mid layui-word-aux labelName"></div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">关联食堂列表：</label>
                <div class="layui-input-inline">
                    <button type="button" class="layui-btn selectProduct">添加</button>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"></label>
                <div class="layui-input-block canteenTable">
                    <table class="layui-hide" id="canteenTable" lay-filter="canteenTable"></table>
                </div>
            </div>
        </form>
    </div>
    <div id="tableForm">
        <form id="tablequeryForm" class="layui-form" action=""></form>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">食堂名称：</label>
                    <div class="layui-input-inline">
                        <input type="text" name="canteenName" autocomplete="off" placeholder="食堂名称" class="layui-input" maxlength="20">
                    </div>
                </div>
                <div class="layui-inline">
                    <button type="button" class="layui-btn searchcanteen">查询</button>
                </div>
            </div>
        </form>
        <table class="layui-hide" id="selectTable" lay-filter="selectTable"></table>
    </div>
</body>
<script type="text/javascript" src="plugins/layui/layui.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
    layui.config({
        base: 'plugins/layui/modules/',
    }).use(['http', 'form', 'table'], function() {
        var http = layui.http,
            form = layui.form,
            table = layui.table;

        var id = http.getPid('id')
        var labelName = http.getPid('name')
        $('.labelName').html(labelName)

        var selectTable,canteenTable;
        var goodsIdSet = [] // 商品id集合
        var goodsIdSetList = []
        var table_data = []

        // 回显已选择的商品列表
        canteenFun()
        function canteenFun() {
            canteenTable = http.table({
                elem: '#canteenTable',
                url: 'supplier/admin/label/relation/canteen/listPage',
                method: 'get',
                id: 'canteenTable',
                where: {
                    supplierLabelId: id 
                },
                cols: [[
                    {title:'序号',type:'numbers'},
                    {field:'canteenName', title: '食堂名称', align : 'center'},
                    {field:'', title: '操作', align : 'center',fixed: 'right',width: 130,
                        templet: function (d) {
                            var html = '';
                            html += '<button type="button" class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del" >删除</button>'
                            return html;
                        }
                    }
                ]]
            })
        }
        // table操作
        table.on('tool(canteenTable)', function(obj){
            if(obj.event=='del'){
                // 删除
                http.myOpen({
                    title:'提示',
                    content:'<p style="text-align:center;margin-top:20px">是否确认删除该关联食堂？</p>',
                    area:['300px','150px'],
                    btn:['确定','取消'],
                    btn1:function(index, layero){
                        http.post('supplier/admin/label/relation/canteen/delete',{
                            labelRelationCanteenId: obj.data.id
                        },function(res){
                            if(res.code == 200){
                                layer.msg('操作成功')
                                layer.close(index)
                                table.reload('canteenTable');
                            }else{
                                layer.msg(res.msg)
                            }
                        })
                        
                    }
                });
            }
        })

        // 选择食堂
        $(document).on('click','.selectProduct',function(){
            
            goodsIdSet = [] // 食堂id集合
            goodsIdSetList = []
            table_data = []
            tableFun()
            http.myOpen({
                title:'选择食堂',
                content: $('#tableForm'),
                area:['850px','720px'],
                btn:['确定','取消'],
                btn1:function(index, layero){
                    if (goodsIdSetList.length == 0) {
                        layer.msg("请勾选需要的食堂");
                        return;
                    }
                    http.postJSON('supplier/admin/label/relation/canteen/check', JSON.stringify(goodsIdSet), function(res) {
                        console.log(res)
                        if(res.code == 200){
                            var params = {
                                supplierLabelId: id,
                                canteenIdSet: goodsIdSet
                            }
                            http.postJSON('supplier/admin/label/relation/canteen/add', JSON.stringify(params), function(res){
                                if(res.code == 200){
                                    layer.msg('操作成功')
                                    layer.close(index)
                                    table.reload('canteenTable');
                                }else{
                                    layer.msg(res.msg)
                                }
                            })
                        }else{
                            onSureSelectCanteen(res.msg)
                        }
                    })
                }
            })
        })
        function onSureSelectCanteen(msg){
            http.myOpen({
                title:'提示',
                content:'<p style="text-align:center;margin:20px 20px 0 20px">' + msg + '，是否将所选食堂移至该等级？</p>',
                area:['300px','200px'],
                btn:['确定','取消'],
                btn1:function(index, layero){
                    var params = {
                        supplierLabelId: id,
                        canteenIdSet: goodsIdSet
                    }
                    http.postJSON('supplier/admin/label/relation/canteen/add', JSON.stringify(params), function(res){
                        if(res.code == 200){
                            layer.msg('操作成功')
                            layer.closeAll();
                            table.reload('canteenTable');
                        }else{
                            layer.msg(res.msg)
                        }
                    })
                    
                }
            });
        }

        // 可选择的食堂列表
        function tableFun(){
            selectTable = http.table({
                elem: '#selectTable',
                url: 'supplier/admin/canteen/supplierListCanteen',
                method: 'get',
                id: 'selectTable',
                done: function(res, curr, count){
                    var data = res.data;
                    table_data = data
                    //在缓存中找到id ,然后设置data表格中的选中状态
                    //循环所有数据，找出对应关系，设置checkbox选中状态
                    for(var i=0;i< res.data.length;i++){
                        for (var j = 0; j < goodsIdSet.length; j++) {
                            //数据id和要勾选的id相同时checkbox选中
                            if(res.data[i].id == goodsIdSet[j]) {
                                //这里才是真正的有效勾选
                                res.data[i]["LAY_CHECKED"]='true';
                                //找到对应数据改变勾选样式，呈现出选中效果
                                var index= res.data[i]['LAY_TABLE_INDEX'];
                                $('#tableForm .layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                                $('#tableForm .layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                            }
                        }
                    }
                    //设置全选checkbox的选中状态，只有改变LAY_CHECKED的值， table.checkStatus才能抓取到选中的状态
                    var checkStatus = table.checkStatus('selectTable');
                    if(checkStatus.isAll){
                        $('#tableForm .layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
                        $('#tableForm .layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');
                    }
                },
                cols: [[
                    {type:'checkbox',fixed: true},
                    {field:'canteenName', title: '食堂名称', align : 'center'}
                ]]
            })
        }
        //复选框选中监听,将选中的id 设置到缓存数组,或者删除缓存数组
        table.on('checkbox(selectTable)', function (obj) {
			var checkStatus = table.checkStatus('selectTable'); //获取选中行状态
            var data = checkStatus.data; //获取选中行数据
			for(var n=0;n<goodsIdSetList.length;n++){
				for(var m=0;m<table_data.length;m++){
					if(goodsIdSetList[n].id == table_data[m].id){
						goodsIdSetList.splice(n,1)
						n--
						break
					}
				}
            }
			var list
			if(goodsIdSetList.length == 0){
				list = data
			}else{
				list = goodsIdSetList.concat(data)
			}
			goodsIdSetList = unique5(list)
			function unique5(arr){
				goodsIdSet=[];
				var hashList=[]
				for (var i = 0; i < arr.length; i++) {
					if(goodsIdSet.indexOf(arr[i].id)==-1){
						goodsIdSet.push(arr[i].id);
						hashList.push(arr[i])
					}
				}
				return hashList;
			}
        });
        
        // 查询
        $(document).on('click','.searchcanteen',function(){
            selectTable.reload({
				page:{curr:1},
				where: {
					canteenName: $('#tableForm input[name=canteenName]').val(),
                }
			})
        })
        
    })
</script>
</html>